<?php
/**
 * Created by PhpStorm.
 * Author: sitewang@aliyun.com
 * CreateTime: 2023/11/6 22:37
 * Blog：www.myblogs.xyz
 */

namespace app\infrastructure\model;

trait UpdateTrait
{
	public function setInc($where = '', $field = '', $number = 1): bool
	{
		return $this->setIncDec(1, $where, $field, $number);
	}

	public function setDec($where = '', $field = '', $number = 1): bool
	{
		return $this->setIncDec(2, $where, $field, $number);
	}

	protected function setIncDec($type = 1, $where = '', $field = '', $number = 0): bool
	{
		if (empty($field)) return false;
		$query = $this->query($where, $field);
		if ($type == 1){
			$query = $query->inc($field, $number);
		}else{
			$query = $query->dec($field, $number);
		}
		if ($query->update()){
			return true;
		}
		return false;
	}

	/**
	 * 状态操作设置
	 * @param string|array $where
	 * @param string $field
	 * @param int $value
	 * @param int $default
	 * @return bool
	 */
	public function status($where = '', string $field = 'status', int $value = 0 , int $default = 1): bool
	{
		$wheres = empty($where) ? self::wheres() : $where;
		$fields = empty($field) ? self::fields() : $field;
		if (empty($wheres)) return false;
		// 数据查询
		$query = $this->db();
		// 批量修改
		if (is_array($wheres)){
			$keys = array_keys($wheres);
			if ($keys['0'] === 0){
				foreach ($wheres as $val){
					$status = $this->getField($val, $fields);
					$new_value = $status == $default ? $value : $default;
					// 主键查询
					if (is_numeric($val)){
						$rows = $query->where($this->pk, $val)->update([$fields=>$new_value]);
					}else{
						$rows = $query->where($val)->update([$fields=>$new_value]);
					}
					if (empty($rows)){
						return false;
					}
				}
			}else{
				$status = $this->getField($wheres, $fields);
				$new_value = $status == $default ? $value : $default;
				$rows = $query->where($wheres)->update([$fields=>$new_value]);
			}
		}elseif (is_numeric($wheres)){
			// 主键查询
			$status = $this->getField($wheres, $fields);
			$new_value = $status == $default ? $value : $default;
			$rows = $query->where($this->pk, $wheres)->update([$fields=>$new_value]);
		}else{
			$status = $this->getField($wheres, $fields);
			$new_value = $status == $default ? $value : $default;
			$rows = $query->where($wheres)->update([$fields=>$new_value]);
		}
		if (empty($rows)){
			return false;
		}
		return true;
	}
}